//
//  WeiBoView.m
//  CloudWeibo
//
//  Created by CLOUD on 11/26/14.
//  Copyright (c) 2014 Cloud. All rights reserved.
//

#import "WeiBoView.h"
#import "UIFactory.h"
#import "WeiBoModel.h"
#import "UIImageView+WebCache.h"
#import "NSString+URLEncoding.h"
#import "UIUtils.h"
#import "UserViewController.h"
#import "WebViewController.h"


#define LIST_FONT   14.0f           //列表中文本字体
#define LIST_REPOST_FONT  13.0f;    //列表中转发的文本字体
#define DETAIL_FONT  18.0f          //详情的文本字体
#define DETAIL_REPOST_FONT 17.0f    //详情中转发的文本字体



@implementation WeiBoView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self _initView];
        _parsedText = [[NSMutableString alloc] init];
    }
    return self;
}

- (void)rtLabel:(id)rtLabel didSelectLinkWithURL:(NSURL*)url
{
    
    NSString *absoluteStr = [url absoluteString];
    if ([absoluteStr hasPrefix:@"http"]) {
        NSLog(@"%@", absoluteStr);
        WebViewController *webViewController = [[WebViewController alloc] initWithUrl:absoluteStr];
        [self.getViewController.navigationController pushViewController:webViewController animated:YES];
        [webViewController release];
        
    } else if ([absoluteStr hasPrefix:@"user"]) {
        NSString *userStr = [url host];
        userStr = [userStr URLDecodedString];
        NSLog(@"%@", userStr);
        
        
        UserViewController *userViewController = [[UserViewController alloc] init];
        userViewController.userName = [userStr substringFromIndex:1];
        [self.getViewController.navigationController pushViewController:userViewController animated:YES];
        [userViewController release];
        
    }  else if ([absoluteStr hasPrefix:@"topic"]) {
        NSString *topicStr = [url host];
        topicStr = [topicStr URLDecodedString];
        NSLog(@"%@", topicStr);
    }

}

- (void) _initView
{
    
    _textLabel = [[RTLabel alloc] initWithFrame:CGRectZero];
    _textLabel.delegate = self;
    _textLabel.font = [UIFont systemFontOfSize:14.0f];
    _textLabel.linkAttributes = [NSDictionary dictionaryWithObject:@"#4595CB" forKey:@"color"];
    _textLabel.selectedLinkAttributes = [NSDictionary dictionaryWithObject:@"darkGray" forKey:@"color"];
    [self addSubview:_textLabel];
    
    
    _image = [[UIImageView alloc] initWithFrame:CGRectZero];
    _image.backgroundColor = [UIColor clearColor];
    _image.image = [UIImage imageNamed:@"page_image_loading.png"];
    _image.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:_image];
    
    _repostBackgroundView = [UIFactory createImageView:@"timeline_retweet_background.png"];
    UIImage *image = [_repostBackgroundView.image stretchableImageWithLeftCapWidth:25 topCapHeight:10];
    _repostBackgroundView.leftCapWidth = 25;
    _repostBackgroundView.topCapHeight = 10;
    _repostBackgroundView.image = image;
    _repostBackgroundView.backgroundColor = [UIColor clearColor];
    [self insertSubview:_repostBackgroundView atIndex:0];
    
    
}



- (void) setWeiBoModel:(WeiBoModel *)weiBoModel
{
    if (_weiBoModel != weiBoModel) {
        [_weiBoModel release];
        _weiBoModel = [weiBoModel retain];
        
    }
    
    if (_repostView == nil) {
        _repostView = [[WeiBoView alloc] initWithFrame:CGRectZero];
        _repostView.isRepost = YES;
        _repostView.isDetail = self.isDetail;
        [self addSubview: _repostView];
    }
    
    [self parseText];
}


- (void) parseText {
    
    [_parsedText setString:@""];
    
    NSString *text = _weiBoModel.text;
    
    
    if (_isRepost) {
        NSString *repostedName = [@"@" stringByAppendingString:_weiBoModel.user.screen_name];
        NSString *repostedUser = [NSString stringWithFormat:@"<a href='user://%@'>%@</a>: ", [repostedName URLEncodedString], repostedName];
        text = [repostedUser stringByAppendingString:text];
    }
    
    text = [UIUtils parseLink:text];
        
    [_parsedText appendString:text];
    
    
}

- (void) layoutSubviews
{
    [super layoutSubviews];
    
    [self renderLable];
    
    [self renderSourceWeiBoView];
    
    [self renderImage];
    
    if (self.isRepost) {
        _repostBackgroundView.frame = self.bounds;
        _repostBackgroundView.hidden = NO;
    } else {
        _repostBackgroundView.hidden = YES;
    }
}

- (void) renderLable
{
    float fontSize = [WeiBoView getFontSize:self.isDetail isRepost:self.isRepost];
    _textLabel.font = [UIFont systemFontOfSize:fontSize];
    _textLabel.frame = CGRectMake(0, 0, self.width, 20);
    if (self.isRepost) {
        _textLabel.frame = CGRectMake(10, 10, self.width-20, 0);
    }
    _textLabel.text = _parsedText;
    //文本内容尺寸
    CGSize textSize = _textLabel.optimumSize;
    _textLabel.height = textSize.height;
}

- (void) renderSourceWeiBoView
{
    WeiBoModel *repostWeibo = _weiBoModel.relWeiBo;
    if (repostWeibo != nil) {
        _repostView.hidden = NO;
        _repostView.weiBoModel = repostWeibo;
        float height = [WeiBoView getWeiboViewHeight:repostWeibo isRepost:YES isDetail:self.isDetail];
        _repostView.frame = CGRectMake(0, _textLabel.bottom, self.width, height);
    }else {
        _repostView.hidden = YES;
    }
}

- (void) renderImage
{
    if (self.isDetail) {
        NSString *bmiddleImage = _weiBoModel.bmiddleImage;
        if (bmiddleImage != nil  && ![@"" isEqualToString:bmiddleImage]) {
            _image.hidden = NO;
            _image.frame = CGRectMake(10, _textLabel.bottom, 280, 200);
            
            [_image setImageWithURL:[NSURL URLWithString:bmiddleImage]];
        } else {
            _image.hidden = YES;
        }
    }else{
        
        NSInteger mode = [[NSUserDefaults standardUserDefaults] integerForKey:kBrowseMode];
        if (mode == 0) {
            mode = SmallBrowseMode;
        }
        if (mode == SmallBrowseMode) {
            NSString *thumbnailImage = _weiBoModel.thumbnailImage;
            if (thumbnailImage != nil  && ![@"" isEqualToString:thumbnailImage]) {
                _image.hidden = NO;
                _image.frame = CGRectMake(10, _textLabel.bottom+10, 70, 80);
                
                [_image setImageWithURL:[NSURL URLWithString:thumbnailImage]];
            } else {
                _image.hidden = YES;
            }
        }else if (mode == LargetBrowseMode) {
            NSString *bmiddleImage = _weiBoModel.bmiddleImage;
            if (bmiddleImage != nil  && ![@"" isEqualToString:bmiddleImage]) {
                _image.hidden = NO;
                _image.frame = CGRectMake(10, _textLabel.bottom+10, self.width-20, 180);
                
                [_image setImageWithURL:[NSURL URLWithString:bmiddleImage]];
            } else {
                _image.hidden = YES;
            }
        }
        
    }
}


//获取字体大小
+ (float)getFontSize:(BOOL)isDetail isRepost:(BOOL)isRepost {
    float fontSize = 14.0f;
    
    if (!isDetail && !isRepost) {
        return LIST_FONT;
    }
    else if(!isDetail && isRepost) {
        return LIST_REPOST_FONT;
    }
    else if(isDetail && !isRepost) {
        return DETAIL_FONT;
    }
    else if(isDetail && isRepost) {
        return DETAIL_REPOST_FONT;
    }
    
    return fontSize;
}


//计数微博视图的高度
+ (CGFloat)getWeiboViewHeight:(WeiBoModel *)weiboModel
                     isRepost:(BOOL)isRepost
                     isDetail:(BOOL)isDetail {
    /**
     *   实现思路：计算每个子视图的高度，然后相加。
     **/
    float height = 0;
    
    //--------------------计算微博内容text的高度------------------------
    RTLabel *textLabel = [[RTLabel alloc] initWithFrame:CGRectZero];
    float fontsize = [WeiBoView getFontSize:isDetail isRepost:isRepost];
    textLabel.font = [UIFont systemFontOfSize:fontsize];
    
    if (isDetail) {
        textLabel.width = kWeibo_Width_Detail;
    } else {
        textLabel.width = kWeibo_Width_List;
    }
    
    if (isRepost) {
        textLabel.width -= 20;
    }
    
    textLabel.text = weiboModel.text;
    
    height += textLabel.optimumSize.height;
    
    //--------------------计算微博图片的高度------------------------
    
    if (isDetail) {
        NSString *bmiddleImage = weiboModel.bmiddleImage;
        if (bmiddleImage != nil && ![@"" isEqualToString:bmiddleImage]) {
            height += (200+10);
        }
    }else{
        
        NSInteger mode = [[NSUserDefaults standardUserDefaults] integerForKey:kBrowseMode];
        if (mode == 0) {
            mode = SmallBrowseMode;
        }
        if (mode == SmallBrowseMode) {
            NSString *thumbnailImage = weiboModel.thumbnailImage;
            if (thumbnailImage != nil && ![@"" isEqualToString:thumbnailImage]) {
                height += (80+10);
            }
        }else if(mode == LargetBrowseMode) {
            NSString *bmiddleImage = weiboModel.bmiddleImage;
            if (bmiddleImage != nil && ![@"" isEqualToString:bmiddleImage]) {
                height += (180+10);
            }
        }
        
        
    }
    
    
    //--------------------计算转发微博视图的高度------------------------
    //转发的微博
    WeiBoModel *relWeibo = weiboModel.relWeiBo;
    if (relWeibo != nil) {
        //转发微博视图的高度
        float repostHeight = [WeiBoView getWeiboViewHeight:relWeibo isRepost:YES isDetail:isDetail];
        height += (repostHeight);
    }
    
    if (isRepost == YES) {
        height += 30;
    }
    
    [textLabel release];
    
    return height;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
